package com.bkhc.umc.service;

import com.bkhc.common.exception.CustomException;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.umc.entity.Role;
import com.bkhc.umc.entity.User;
import com.bkhc.umc.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleSerivce {

    @Autowired
    private RoleRepository repository;


    public ResultJson<?> queryRole(Role role, int pageIndex, int pageSize) {
        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
        PageRequest pageRequest = PageRequest.of(pageIndex-1, pageSize, Sort.by(orders));
        Page<Role> roles = null;
        if(role == null){
            roles = repository.findAll(pageRequest);
        }else {
            roles = repository.findAll(role, pageRequest);
        }
        ResultJson<Page<Role>> resultJson = ResultJson.success();
        resultJson.setData(roles);
        return  resultJson;
    }

    public ResultJson<?> add(Role role) {
        if(role == null){
            ResultJson<User> resultJson = ResultJson.failure(ResultCode.BAD_REQUEST);
            return resultJson;
        }
        int count = repository.find(role.getRoleCode(),role.getRoleName());
        if(count>0){
            ResultJson<User> resultJson = ResultJson.failure(ResultCode.ISEXIT_RESURCE);
            return resultJson;
        }
        repository.save(role);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> delete(Role role) {
        repository.delete(role);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    /**
     * 返回当前人机请求，哪些角色拥有权限，返回roleCode
     */
    public List<String> getRoleCode(String operationCode){
        List<String> rolecodes = repository.findRoleCode(operationCode);
        return rolecodes;
    }
}
